package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Employee;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.service.IEmployeeService;
import com.itheima.util.Result;
import com.itheima.util.UserDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;

import java.time.LocalDateTime;

import java.util.concurrent.TimeUnit;

import static com.itheima.util.RedisConstants.LOGIN_CODE_KEY;
import static com.itheima.util.RedisConstants.LOGIN_CODE_TTL;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login( @RequestBody Employee employee) {
        //1、将页面提交的密码password进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee selectOne = employeeMapper.selectOne(lqw);
        //3、如果没有查询到则返回登录失败结果
        if (selectOne == null){
            return Result.error("登录失败，用户名不存在");
        }
        //4、密码比对，如果不一致则返回登录失败结果
        if (!selectOne.getPassword().equals(password)){
            return Result.error("登录失败，密码不正确");
        }
        //5、查看员工状态，如果为已禁用状态，则返回员工已禁用的结果
        if (selectOne.getStatus()!=1){
            return Result.error("登录失败，该账号正在使用");
        }
        //6、登录成功，将用户的id存入redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY,selectOne.getId().toString());
        //7、设置有效期
        stringRedisTemplate.expire(LOGIN_CODE_KEY,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //查询到的信息复制到当前登录用户的类中
        UserDTO userDTO = BeanUtil.copyProperties(selectOne, UserDTO.class);

        return Result.success(userDTO);
    }

    @Override
    public Result saveEmployee(Employee employee) {
        LambdaQueryWrapper<Employee> lqw1 = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Employee> lqw2 = new LambdaQueryWrapper<>();
        lqw1.eq(Employee::getUsername,employee.getUsername());
        lqw2.eq(Employee::getPhone,employee.getPhone());
        //查看用户名是否重复
        Employee userNameOne = employeeMapper.selectOne(lqw1);
        if (userNameOne != null){
            return Result.error("用户名已经重复");
        }
        //查看手机号是否重复
        Employee phoneOne = employeeMapper.selectOne(lqw2);
        if (phoneOne != null){
            return Result.error("手机号已经重复");
        }
        //获取当前登录者的id
        String id = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY);
        Long userId = Long.valueOf(id);
        //添加创建人信息
        employee.setCreateUser(userId);
        employee.setUpdateUser(userId);
        //设置默认密码”123456“
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //设置创建时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setStatus(1);
        int insert = employeeMapper.insert(employee);
        if (insert<=0){
            return Result.error("添加失败！");
        }
        return Result.success(employee);
    }

    @Override
    public Result findOne(Long id) {
        Employee employee = employeeMapper.selectById(id);
        if (employee == null){
            return Result.error("id为"+id+"的用户不存在");
        }
        return Result.success(employee);
    }

    @Override
    public Result updateOne(Employee employee) {
        //获取当前登录者的id
        String id = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY);
        Long userId = Long.valueOf(id);
        if (employee.getUsername()==null
                &&employee.getName()==null
                &&employee.getPhone()==null
                &&employee.getSex()==null
                &&employee.getIdNumber()==null){
            employee.setStatus(employee.getStatus());

            employee.setUpdateUser(userId);
            employee.setUpdateTime(LocalDateTime.now());
            int i = employeeMapper.updateById(employee);
            if (i<=0){
                return Result.error("修改失败");
            }
            return Result.success(employee);
        }
        employee.setUpdateUser(userId);
        employee.setUpdateTime(LocalDateTime.now());
        int i = employeeMapper.updateById(employee);
        if (i<=0){
            return Result.error("修改失败");
        }
        return Result.success(employee);
    }

    @Override
    public Result logout() {

        //从redis中删除，当前用户登录的信息
        stringRedisTemplate.delete(LOGIN_CODE_KEY);

        return Result.success("退出登录成功！");
    }

    @Override
    public IPage<Employee> getPage(int current, int pageSize, String name) {
        if (name != null){
            LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Employee::getUsername,name);
            IPage<Employee> page = new Page<Employee>(current,pageSize);
            return employeeMapper.selectPage(page,lqw);
        }
        IPage<Employee> page = new Page<Employee>(current,pageSize);
        return employeeMapper.selectPage(page,null);
    }
}
